Add & Show data in Java ArrayList [closed]

Posted by Kaidul Islam Sazal on Programmers See other posts from Programmers or by Kaidul Islam Sazal
Published on 2012-10-23T19:33:00Z Indexed on 2012/10/23 23:18 UTC
Read the original article Hit count: 233

Filed under:

I have a class inside a main class :

static class Graph{
    static int u, v, cost;
}

I have instantiated an arraylist of the class:

static List<Graph> g = new ArrayList<Graph>();

And I insert several values into the arraylist like this:

Scanner input = new Scanner(System.in);
    for (int i = 0; i < edge_no; i++) {
        Graph e = new Graph();
        e.u = input.nextInt();
        e.v = input.nextInt();
        e.cost = input.nextInt();
        g.add(e);
    }

And I print it like this:

    for (int i = 0; i < edge_no; i++) {
    System.out.println(g.get(i).u + " " + g.get(i).v + " " + g.get(i).cost);
    }

But the problem is that, when I print it, only the last value is shown all the time.It seems that, all the previous values are over-written with it.

Input :

1 2 5
1 3 8
2 3 9

Output: 

2 3 9
2 3 9
2 3 9

Expected output is just like the input.But I can't fix the problem as I am novice in java.

© Programmers or respective owner

Related posts about java